﻿using JetBrains.Annotations;
using System.Linq;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Aspects;
using Orchard.ContentManagement.Drivers;
using Contrib.Chapters.Models;
using Contrib.Chapters.Services;

namespace Contrib.Chapters.Drivers {
    [UsedImplicitly]
    public class ChapterPartDriver : ContentPartDriver<ChapterPart> {
        private readonly IChapterService _chapterService;

        public ChapterPartDriver(IChapterService chapterService) {
            _chapterService = chapterService;
        }

        protected override string Prefix { get { return "Chapter"; } }

        protected override DriverResult Display(ChapterPart part, string displayType, dynamic shapeHelper) {

            return Combined(
                ContentShape("Parts_Chapters_Navigation",
                    () => {
                        var book = _chapterService.GetBook(part.Record.Book.Id);
                        var chapters = _chapterService.GetChapters(book).Select((c, i) => new {Chapter = c, Index = i}).ToList();
                        var position = chapters.Where(c => c.Chapter == part).Select(c => c.Index).First();

                        var next = chapters.Where(c => c.Index == position + 1).Select(c => c.Chapter).FirstOrDefault();
                        var previous = chapters.Where(c => c.Index == position - 1).Select(c => c.Chapter).FirstOrDefault();

                        return shapeHelper.Parts_Chapters_Navigation(ContentPart: part, Next: next, Previous: previous, Parent: part.Container.As<IRoutableAspect>());
                    }),
                ContentShape("Parts_Chapters_Sections",
                    () => {
                        var sections = _chapterService.GetDirectChildren(part);
                        return shapeHelper.Parts_Chapters_Sections(ContentPart: part, Sections: sections);
                    })
                );
        }

        protected override DriverResult Editor(ChapterPart part, dynamic shapeHelper) {
            return ContentShape("Parts_Chapters_Fields",
                () => shapeHelper.EditorTemplate(TemplateName: "Parts/Chapters.Fields", Model: part, Prefix: Prefix));
        }

        protected override DriverResult Editor(ChapterPart part, IUpdateModel updater, dynamic shapeHelper) {
            updater.TryUpdateModel(part, Prefix, null, null);
            return Editor(part, shapeHelper);
        }
    }
}